import { localExtensionStorage } from '@/common/extension-storage'
export const defaultSettings: Record<string, unknown> = {
  sms: {
    lock: false,
  },
}

export function getSetting(namespace: string, key: string) {
  return new Promise<unknown>((resolve) => {
    const realKey = `${namespace}_${key}`
    localExtensionStorage.get(realKey).then((result) => {
      if (result && Object.keys(result).length > 0) {
        resolve(result[realKey])
      } else {
        try {
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          resolve(defaultSettings[namespace][key])
        } catch (err) {
          throw new Error(`无法查询到配置, key: ${namespace}_${key}`)
        }
      }
    })
  })
}

export function setSetting(namespace: string, key: string, value: unknown) {
  return new Promise<unknown>((resolve, reject) => {
    const realKey = `${namespace}_${key}`
    localExtensionStorage
      .set(realKey, value)
      .then((result) => {
        resolve(result)
      })
      .catch(reject)
  })
}

export default {
  getSetting,
  setSetting,
}
